package com.ysxsoft.wdg.ui.activity.center_st;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.socks.library.KLog;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.response.StOrderStatusDetailResponse;
import com.ysxsoft.wdg.bean.zy.CreateIdBean;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.pay.PayListenerUtils;
import com.ysxsoft.wdg.pay.PayResultListener;
import com.ysxsoft.wdg.pay.PayUtils;
import com.ysxsoft.wdg.pay.WxPayBean;
import com.ysxsoft.wdg.ui.activity.center_zy.ZyGoodsConfirmActivity;
import com.ysxsoft.wdg.ui.activity.login.LoginValid;
import com.ysxsoft.wdg.ui.activity.my.CouponListActivity;
import com.ysxsoft.wdg.ui.activity.order.StOrderStatusDetailActivity;
import com.ysxsoft.wdg.ui.activity.th.tuan.TuanIntroActivity;
import com.ysxsoft.wdg.util.BigDecimalUtil;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.delayaction.Action;
import com.ysxsoft.wdg.util.delayaction.SingleCall;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.alertview.AlertUtils;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class StGoodsConfirmActivity extends BaseActivity implements PayResultListener {

    public static void start(Context context, String name, String productid, String onePrice, int num, int store,String companyid,String ruleId,String productPic,String roleName) {
        Intent intent = new Intent(context, StGoodsConfirmActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("productid", productid);
        intent.putExtra("onePrice", onePrice);
        intent.putExtra("num", num);
        intent.putExtra("store", store);
        intent.putExtra("companyid", companyid);
        intent.putExtra("ruleId", ruleId);
        intent.putExtra("productPic", productPic);
        intent.putExtra("roleName", roleName);
        context.startActivity(intent);
    }


    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_one_money)
    TextView tvOneMoney;
    @BindView(R.id.edit_goods_sub)
    ImageView iv_del;
    @BindView(R.id.edit_goods_num)
    TextView tvGoodsNum;
    @BindView(R.id.edit_goods_plus)
    ImageView iv_add;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_yuE)
    TextView tvYuE;
    @BindView(R.id.iv_yuE_choose)
    ImageView ivYuEChoose;
    @BindView(R.id.tv_zfb)
    TextView tvZfb;
    @BindView(R.id.coupon)
    TextView coupon;
    @BindView(R.id.couponLayout)
    LinearLayout couponLayout;
    @BindView(R.id.iv_zfb_choose)
    ImageView ivZfbChoose;
    @BindView(R.id.iv_wx_choose)
    ImageView ivWxChoose;@BindView(R.id.proImage)
    ImageView proImage;
    @BindView(R.id.role)
    TextView role;

    private String name = "", onePrice = "", totalPrice = "", uid = "", productid = "";
    private int num = 1, store = 2, payType = 0;
    private String orderId = "0";
    private String companyid = "0";
    private String ruleId = "0";
    private String productPic = "";
    private String roleName = "";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    tvGoodsNum.setText(num + "");
                    totalPrice = BigDecimalUtil.formatDoubleScale(BigDecimalUtil.mul(Double.parseDouble(onePrice), num));
                    tvTotalMoney.setText(getString(R.string.price_rmb, totalPrice));
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_st_goods_confirm;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("确认订单");
        ivYuEChoose.setSelected(true);

        uid = SharePrefUtils.getUserId();

        Intent intent = getIntent();
        name = intent.getStringExtra("name");
        productid = intent.getStringExtra("productid");
        onePrice = intent.getStringExtra("onePrice");
        num = intent.getIntExtra("num", 1);
        store = intent.getIntExtra("store", 2);
        companyid = intent.getStringExtra("companyid");
        ruleId = intent.getStringExtra("ruleId");
        productPic = intent.getStringExtra("productPic");
        roleName = intent.getStringExtra("roleName");

        tvName.setText(name);
        tvOneMoney.setText(getString(R.string.price_rmb, onePrice));
        role.setText(roleName);

        Glide.with(StGoodsConfirmActivity.this).load(productPic).into(proImage);
        handler.sendEmptyMessage(0);
    }

    @OnClick({R.id.title_finish, R.id.edit_goods_sub, R.id.edit_goods_plus,
            R.id.ll_pay_yuE, R.id.ll_pay_zfb, R.id.ll_pay_wx, R.id.btn_sure, R.id.couponLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.edit_goods_sub:
                if (num <= 1) {
                    return;
                }
                num--;
                handler.sendEmptyMessage(0);
                break;
            case R.id.edit_goods_plus:
                if (num >= store) {
                    ToastUtils.showToast("库存不足");
                    return;
                }
                num++;
                handler.sendEmptyMessage(0);
                break;
            case R.id.ll_pay_yuE:
                ivYuEChoose.setSelected(true);
                ivZfbChoose.setSelected(false);
                ivWxChoose.setSelected(false);

                payType = 0;

                break;
            case R.id.ll_pay_zfb:
                ivYuEChoose.setSelected(false);
                ivZfbChoose.setSelected(true);
                ivWxChoose.setSelected(false);

                payType = 1;

                break;
            case R.id.ll_pay_wx:
                ivYuEChoose.setSelected(false);
                ivZfbChoose.setSelected(false);
                ivWxChoose.setSelected(true);

                payType = 2;

                break;
            case R.id.btn_sure:
                if (orderId.equals("0") || TextUtils.isEmpty(orderId)) {
                    createOrder();
                } else {
                    toPay();
                }
                break;
            case R.id.couponLayout://点击优惠券
                Intent intent=new Intent(this, CouponListActivity.class);
                intent.putExtra("account",totalPrice);
                intent.putExtra("companyid",companyid);
                startActivityForResult(intent,0x01);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0x01){
            if(data!=null){
                 couponId=data.getStringExtra("couponId");
            }
        }
    }
    String couponId;

    private void toPay() {
        KLog.e("uid=" + uid + ", orderId=" + orderId + ", totalPrice=" + totalPrice);
        switch (payType) {
            case 0:
                postPayYue();
                break;
            case 1:
                postPayZfb();
                break;
            case 2:
                postPayWx();
                break;
        }
    }

    private void createOrder() {
        mApiHelper.createStOrder(uid,totalPrice,ruleId,  num + "", companyid, new Observer<BaseBean<CreateIdBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseBean<CreateIdBean> baseBean) {
                        if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                            CreateIdBean data = baseBean.getData();

                            orderId = data.getOrderid();

                            toPay();
                        } else {
                            ToastUtils.showToast(baseBean.getMs());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showToast("请稍后再试");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /***
     * 实体订单微信支付
     */
    private void postPayWx() {
        if(couponId==null){
            couponId="";
        }
        mApiHelper.payStWx(uid, orderId, totalPrice,couponId, new Observer<BaseBean<WxPayBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<WxPayBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
//                    PayUtils.getInstance(mContext).pay((Activity) mContext,
//                            PayUtils.PAY_TYPE_WX, "", baseBean.getData());
                    PayUtils.getInstance(mContext).toWxPay(baseBean.getData());
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void postPayZfb() {
        mApiHelper.payStZfb(uid, orderId, totalPrice,couponId, new Observer<BaseBean<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<String> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    PayUtils.getInstance(mContext).pay((Activity) mContext,
                            PayUtils.PAY_TYPE_ALI, baseBean.getData(), null);
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void postPayYue() {
        if(couponId==null){
            couponId="";
        }
        mApiHelper.payStYuE(uid, orderId, totalPrice,couponId, new Observer<BaseBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    PayListenerUtils.getInstance(mContext).addSuccess();
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    protected void setListener() {
        PayListenerUtils.getInstance(this).addListener(this);
    }


    private void toOrderDetail() {

        AlertUtils.dismissAlert();
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                StOrderStatusDetailActivity.start(mContext,orderId);
            }
        });
        finish();
    }

    @Override
    public void onPaySuccess() {
        ToastUtils.showToast("支付成功");
        toOrderDetail();
    }

    @Override
    public void onPayError() {
        ToastUtils.showToast("支付失败");
//        toOrderDetail();
    }

    @Override
    public void onPayCancel() {
        ToastUtils.showToast("取消支付");
//        toOrderDetail();
    }


    @Override
    protected void onDestroy() {
        PayListenerUtils.getInstance(mContext).removeListener(this);
        super.onDestroy();
    }

}
